package org.fpaadmin.web;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.cycle.RequestCycleContext;

public class JpaRequestCycle extends RequestCycle {

    private EntityManager em;
    private EntityManagerFactory emf;

    public static JpaRequestCycle get() {
	return (JpaRequestCycle) RequestCycle.get();
    }

    public JpaRequestCycle(EntityManagerFactory emf, RequestCycleContext context) {
	super(context);
	this.emf = emf;
    }

    public EntityManager getEntityManager() {
	if (em == null) {
	    em = emf.createEntityManager();
	    em.getTransaction().begin();
	}
	return em;
    }

    @Override
    protected void onEndRequest() {
	super.onEndRequest();
	if (em != null) {
	    if (em.getTransaction().isActive()) {
		em.getTransaction().commit();
	    }
	    em.close();
	}
    }

}
